package com.chum.chamber.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;

import com.chum.chamber.model.Login;
import com.chum.chamber.service.LoginService;
import com.chum.chamber.service.LoginServiceImpl;
import com.chum.chamber.validator.LoginValidator;

@Controller
@RequestMapping("/login.htm")
public class LoginController {

	LoginValidator loginValidator;
	LoginService loginService;
	
	@Autowired
	public LoginController(LoginValidator loginValidation, LoginService loginService) {
		this.loginValidator = loginValidation;
		this.loginService = loginService;
	}
	
	@ExceptionHandler
	@RequestMapping(method = RequestMethod.POST)
	public String loginSubmit(@ModelAttribute("login")Login login, BindingResult result, SessionStatus status) {
		
		loginValidator.validate(login, result);
		
		if (result.hasErrors()) {
			//if validator failed
			return "LoginForm";
		} else {
			if (loginService.validateUser(login)) {
				status.setComplete();
			} else {
				return "LoginForm";
			}
			//form success
			return "HomeForm";
		}
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String initForm(ModelMap model){
		Login login = new Login();
		model.addAttribute("login", login);
		return "LoginForm";
	}
}
